<template>
  <el-dialog v-model="dialogVisible" title="上传文件" width="500px" @close="reset">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="文件" prop="file">
        <el-upload
          class="upload-box"
          drag
          :auto-upload="false"
          :limit="1"
          :file-list="fileList"
          :on-change="handleChange"
          :on-remove="handleRemove"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或点击上传</div>
        </el-upload>
      </el-form-item>

      <el-form-item label="标签">
        <el-select v-model="form.tags" multiple filterable collapse-tags placeholder="请选择标签">
          <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.id" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="submit">上传</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { getTags } from '@/api/tags'
import { uploadDoc } from '@/api/files'
import { useDocsStore } from '@/stores/DocsStore.js'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: Boolean,
})
const emit = defineEmits(['update:modelValue'])

const dialogVisible = ref(false)

watch(
  () => props.modelValue,
  (val) => (dialogVisible.value = val),
)
watch(dialogVisible, (val) => emit('update:modelValue', val))

const fileList = ref([])
const form = reactive({
  file: null,
  type: '',
  tags: [],
})

const formRef = ref()
const tags = ref([])

const rules = {
  file: [{ required: true, message: '请选择文件', trigger: 'change' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
}

const handleChange = (uploadFile) => {
  form.file = uploadFile.raw
  fileList.value = [uploadFile]
}

const handleRemove = () => {
  form.file = null
  fileList.value = []
}

const fetchTags = async () => {
  try {
    const res = await getTags()
    tags.value = res.data
  } catch (err) {
    console.error('获取标签失败', err)
  }
}

const reset = () => {
  form.file = null
  form.type = ''
  form.tags = []
  fileList.value = []
}

const close = () => {
  emit('update:modelValue', false)
}

const submit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      const formData = new FormData()
      formData.append('file', form.file)
      form.tags.forEach((tag) => formData.append('tags', tag))

      await uploadDoc(formData)

      ElMessage.success('上传成功')
      close()
      reset()
    } catch (e) {
      console.error(e)
      ElMessage.error('上传失败')
    } finally {
      useDocsStore().triggerRefresh()
    }
  })
}

onMounted(() => {
  fetchTags()
})
</script>

<style scoped>
.upload-box {
  width: 100%;
}
</style>
